/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Utility class collecting static methods related to spring's context.
 *
 */

public final class AppContext implements ApplicationContextAware {
	

    private static final Logger logger = LoggerFactory.getLogger(AppContext.class);
    
    private static ApplicationContext _appContext;

    // Private constructor prevents instantiation from other classes
    private AppContext() {
    }
    
    /* (non-Javadoc)
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
    	logger.info("Initializing AppContext Application Context");
        _appContext = appContext;
    }

    /**
     * Retrieves a bean registered in the Spring context.
     * 
     * @param id
     *            The bean identifier
     * @return The bean instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String id) {
    	logger.info("Trying to retrieve Bean ID : " + id);
    	T bean = (T) _appContext.getBean(id);
    	if(bean != null) {
        	logger.info("Bean found: " + bean.toString());
    	} else {
        	logger.info("Bean NOT FOUND");
    	}
        return bean;
    }
    
    public static String[] getBeanNames(Class<?> beanClass) {
    	logger.info("Trying to retrieve Beans of Class : " + beanClass.getName());
        String[] beanNames = _appContext.getBeanNamesForType(beanClass);
        
        return beanNames;
    }
}
